package com.zhaungjie.base.utils;

import com.zhaungjie.base.utils.PropertiesCopyUtils.PropertiesCopy;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class InstanceCloseUtils {
    /**
     * 深度复制
     *
     * @param original 起初
     * @return {@link InstanceCloseUtils}
     * @throws IOException            IOException
     * @throws ClassNotFoundException 未找到类异常
     */
    public static<T> T DeepCopy(T original) throws IOException, ClassNotFoundException {
        //将对象写入流中
        ByteArrayOutputStream bo=new ByteArrayOutputStream();
        ObjectOutputStream oo=new ObjectOutputStream(bo);
        oo.writeObject(original);

        //从流中取出
        ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi=new ObjectInputStream(bi);
        return (T)oi.readObject();
    }

    /**
     * 浅拷贝（对属性进行拷贝）
     * 前提：T implements Cloneable
     */
    public static <T> T shallowCopy(T original) throws InstantiationException, IllegalAccessException {
        if (original == null) return null;
        // 如果不异常，得到的肯定是与original相同类的对象
        return (T)PropertiesCopy.type(Object.class, original.getClass())
                .produce(original);
    }

    public static<T> List<T> shallowCopy(T original, Integer number, boolean isContainOriginal) {
        List<T> instances = new ArrayList<>(number);
        if(isContainOriginal) {
            instances.add(original);
            number--;
        }
        for (Integer i = 0; i < number; i++) {
            T instance = (T)PropertiesCopy.type(Object.class, original.getClass())
                    .produce(original);
            instances.add(instance);
        }
        return instances;
    }
}
